package com.yun.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author xiao
 * 全局异常处理器，底层是代理模式，代理Controller
 * @ControllerAdvice 通知，指定拦截加了RestController的类
 * @ResponseBody 用于返回JSON数据
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * @ExceptionHandler 用于设置该方法处理哪些异常
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandle(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        if (ex.getMessage().contains("Duplicate entry")){
            //如果异常信息中包含Duplicate entry，就说明违反了唯一性约束
            //将违反约束的字段信息提取出来：zhangsan
            String[] s = ex.getMessage().split(" ");
            String message = s[2]+"已存在！";
            return R.error(message);
        }
        return R.error("未知错误！");
    }

    /**
     * 处理自定义的业务异常
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandle(CustomException exception){

        return R.error(exception.getMessage());
    }
}
